package lv.dysnomia.songs.server.wiki

import scala.collection.immutable.Queue

object WikiParser {
  val separators: Array[Char] = Array('\n')

  def parse(wiki: String): List[WikiBlock] = {
    val lines: Array[String] = wiki.split(separators)
    var listType = '#'
    val buffer = new Buffer

    var q = 0
    for (line <- lines) {
      if (q == 0 && lineType(line) == ' ') {
        q = 0
      } else if (q == 0 && (lineType(line) == '#' || lineType(line) == '*')) {
        listType = lineType(line)
        buffer.startListBlock(line)
        q = 1
      } else if (q == 0 && lineType(line) == 'p') {
        buffer.startPBlock(line)
        q = 2
      } else if (q == 1 && lineType(line) == ' ') {
        buffer.endListBlock(listType)
        q = 0
      } else if (q == 1 && (lineType(line) == '#' || lineType(line) == '*')) {
        if (listType == lineType(line)) {
          buffer.appendToListBlock(line)
        } else {
          // list type changes from '#' to '*' or vice versa
          buffer.endListBlock(listType)
          listType = lineType(line)
          buffer.startListBlock(line)
        }
        q = 1
      } else if (q == 1 && lineType(line) == 'p') {
        buffer.appendToListItem(line)
        q = 1
      } else if (q == 2 && lineType(line) == ' ') {
        buffer.endPBlock()
        q = 0
      } else if (q == 2 && (lineType(line) == '#' || lineType(line) == '*')) {
        buffer.endPBlock()
        listType = lineType(line)
        buffer.startListBlock(line)
        q = 1
      } else if (q == 2 && lineType(line) == 'p') {
        buffer.appendToP(line)
        q = 2
      }
    }
    if (q == 1) {
      buffer.endListBlock(listType)
    } else if (q == 2) {
      buffer.endPBlock()
    }
    buffer.getWikiBlocks
  }

  def lineType(line: String): Char = {
    if (line.trim.equals("")) ' '
    else if (line.trim.startsWith("#")) '#'
    else if (line.trim.startsWith("*")) '*'
    else 'p'
  }

  def replace(line: String): String = {
    return line.replaceFirst("^# +", "")
  }

  def parseExpr(expr: String): WikiExpr = {
	val expr1 = expr.trim.replaceFirst("^# *","")
	val expr2 = expr1.replaceFirst("^\\* *","")
    WikiExprParser.parseExpr(expr2)
  }
}